<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\ValidateException;

/**
 * 产品接口
 */
class ProductDownload extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function addProductDownloadById($productId = NULL)
    {
        if (!$productId) {
            $this->error(__('Parameter %s can not be empty', 'productId'));
        }
        $product = model('\app\admin\model\jy\Product')->where('id', $productId)->find();
        if (!$product) {
            $this->error(__('No Results were found'));
        }
        $userId = $this->auth->id;
        $today = date("Y-m-d", time());
        $row = model('\app\admin\model\jy\ProductDownload')->where(['product_id' => $productId, 'user_id' => $userId, 'create_time' => ['>=', $today]])->find();
        if ($row) {
            $row['update_time'] = date("Y-m-d H:i:s", time());
            $row->isUpdate(true)->save();
            $this->success('', $row);
        }
        Db::startTrans();
        try {
            model('\app\admin\model\jy\ProductDownload')->insert(['product_id' => $productId, 'user_id' => $userId]);
            $product['download_count'] = $product['download_count'] + 1;
            $row = model('\app\admin\model\jy\ProductDownload')->where(['product_id' => $productId, 'user_id' => $userId])->find();
            if (!$row) {
                $product['download_user_count'] = $product['download_user_count'] + 1;
            }
            $product['update_time'] = date("Y-m-d H:i:s", time());
            $product->isUpdate(true)->save();
            Db::commit();
            $this->success();
        } catch (ValidateException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function getUserProductDownloadList()
    {
        $user = $this->auth->getUser();
        $pageIndex = $this->request->post('pageIndex', 1);
        $pageSize = $this->request->post('pageSize', 10);
        $list = model('\app\admin\model\jy\ProductDownload')
            ->with('product')
            ->where('product.is_del = 0')
            ->where("user_id", $user['id'])
            ->order('update_time desc')
            ->paginate($pageSize, false, ['page' => $pageIndex]);
        $newList = [];
        $curDate = date('Y年m月d日');
        if ($list) {
            foreach ($list as $key => $l) {
                $newList[$key] = [
                    'id'           => $l['id'],
                    'product_id'   => $l['product_id'],
                    'product_name' => $l['product']['product_name'],
                    'date'         => date('Y年m月d日', strtotime($l['update_time'])),
                    'user_id'      => $l['user_id'],
                    'cover_images' => cdnurl($l['product']['cover_images']),
                ];
                if ($newList[$key]['date'] == $curDate) {
                    $newList[$key]['date'] = '今天';
                }
            }
        }
        $result = array("total" => $list->total(), "rows" => $newList);
        $this->success('', $result);
    }

    public function delProductDownloadByIds()
    {
        $user = $this->auth->getUser();
        $ids = $this->request->post('ids');
        if (!trim($ids)) {
            $this->error(__('Parameter error'));
        }
        $res = model('\app\admin\model\jy\ProductDownload')->where(['user_id' => $user->id, 'id' => ['in', $ids]])->delete();
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function delProductDownloadAll()
    {
        $user = $this->auth->getUser();
        $res = model('\app\admin\model\jy\ProductDownload')->where(['user_id' => $user->id])->delete();
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function getProductDownloadList()
    {
        $pageIndex = $this->request->post('pageIndex', 1);
        $pageSize = $this->request->post('pageSize', 10);
        $startDate = $this->request->post('startDate');
        $endDate = $this->request->post('endDate');
        $keyword = $this->request->post('keyword');
        $user = $this->auth->getUser();
        // 普通用户
        $where = [];
        if ($user['group_id'] == 2) {
            $where['user_id'] = $user['id'];
        }
        if ($keyword) {
            $where['product.product_name'] = ['like', '%' . $keyword . '%'];
        }
        if ($startDate && $endDate) {
            $where['product_download.update_time'] = ['between time', [$startDate, $endDate . ' 23:59:59']];
        }
        $list = model('\app\admin\model\jy\ProductDownload')
            ->field('*, DATE_FORMAT(product_download.update_time, "%Y-%m-%d") create_date, count(product_download.user_id) scan_count')
            ->with('product')
            ->where('product.is_del = 0')
            ->where($where)
            ->group('DATE_FORMAT(product_download.update_time, "%Y-%m-%d"), product_download.product_id')
            ->order('create_date desc')
            ->paginate($pageSize, false, ['page' => $pageIndex]);
        $newList = [];
        if ($list) {
            foreach ($list as $item) {
                $newList[] = [
                    'product_id'   => $item['product_id'],
                    'date'         => date('Y年m月d日', strtotime($item['create_time'])),
                    'product_name' => $item['product']['product_name'],
                    'cover_images' => cdnurl($item['product']['cover_images']),
                    'scan_count'   => $item['scan_count']
                ];
            }
        }
        $result = array("total" => $list->total(), "rows" => $newList);
        $this->success('', $result);
    }

    public function getProductDownloadListByProductId()
    {
        $pageIndex = $this->request->post('pageIndex', 1);
        $pageSize = $this->request->post('pageSize', 10);
        $productId = $this->request->post('productId');
        $user = $this->auth->getUser();
        // 是否是超级管理员
        if ($user['group_id'] == 2) {
            $this->error(__('You have no permission'));
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        $list = model('\app\admin\model\jy\ProductDownload')
            ->field('*')
            ->with(['user'])
            ->where('product_download.product_id', $productId)
            ->order('product_download.update_time desc')
            ->paginate($pageSize, false, ['page' => $pageIndex]);
        $newList = [];
        if ($list) {
            foreach ($list as $item) {
                $newList[] = [
                    'id'         => $item['id'],
                    'date'       => date('Y年m月d日', strtotime($item['update_time'])),
                    'time'       => date('G:i', strtotime($item['update_time'])),
                    'product_id' => $item['product_id'],
                    'user_id'    => $item['user']['id'],
                    'avatar'     => cdnurl($item['user']['avatar']),
                    'nickname'   => $item['user']['nickname'],
                ];
            }
        }
        $result = array("total" => $list->total(), "rows" => $newList);
        $this->success('', $result);
    }
}